package mp

import (
	"duoke/context"
	"duoke/model"
	"duoke/service"
	"duoke/utils/gconv"
	"duoke/utils/response"
	"duoke/utils/valid"
	"duoke/utils/yaml"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

var Order = new(orderCtl)

type orderCtl struct{}

// 创建支付订单
func (ctl *orderCtl) Create(c *gin.Context) {
	var req model.ReqOrderCreate
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	// 验证表单是否填写
	for _, v := range req.Form {
		//t := reflect.TypeOf(v.Value).String()
		//if t == "[]interface {}" {
		//	p, _ := v.Value.([]interface{})
		//	if len(p) == 0 {
		//		response.Error(c, "请填写"+v.Name, nil)
		//		return
		//	}
		//}
		//if t == "string" {
		//	if v.Value == "" {
		//		response.Error(c, "请填写"+v.Name, nil)
		//		return
		//	}
		//}
		if v.Name == "手机号" {
			p, _ := v.Value.(string)
			if !valid.IsMobile(p) {
				response.Error(c, v.Name+"不正确", nil)
				return
			}
		}
		if v.Name == "地址" {
			if gconv.String(v.Value) == "" {
				response.Error(c, v.Name+"不正确", nil)
				return
			}
		}
	}
	// 创建订单数据
	order, err := service.Order.Create(c, req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	// 获取支付参数
	notifyUrl := context.Global.Domain + "/mp/notify/wxpay"
	config := yaml.GetConfig()
	if config.SubMch.SubType == "2" {
		order.SubMchId = ""
	}

	payConf, err := service.WechatPay.OrderV2(c, notifyUrl, order.Openid, order.OrderNo, order.PayAmount, "pintuan", order.SubMchId)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", gin.H{
		"pay":   payConf,
		"order": order,
	})
}

// 已经购买订单
func (ctl *orderCtl) List(c *gin.Context) {
	goods, _ := service.Request.Goods(c)
	where := "goods_id = " + gconv.String(goods.Id)
	where += " AND pay_state = 1"
	list, err := service.Order.List(c, where, 50, "id,name,group_id,nickname,avatar,group_num,pay_amount,pay_time,is_head,created_at")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	for index, value := range list {
		if value.IsHead == 0 {
			head, _ := service.Order.GetById(c, value.GroupId, "id,name,nickname,avatar,group_num")
			if head != nil && head.Id > 0 {
				list[index].Head = head
			}
		}
	}
	response.Success(c, "success", list)
}
